package com.hzhk.happyrent.ui.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hzhk.happyrent.R;
import com.hzhk.happyrent.bean.order.OrderInfoModel;
import com.hzhk.happyrent.bean.person.AddressDefaultBean;
import com.hzhk.happyrent.bean.rent.BaseModel;
import com.hzhk.happyrent.network.API;
import com.hzhk.happyrent.network.HttpManager;
import com.hzhk.happyrent.network.MyStringResponse;
import com.hzhk.happyrent.network.MyStringTransResponse;
import com.hzhk.happyrent.ui.activity.personal.AddressActivity;
import com.hzhk.happyrent.ui.view.ClearEditText;
import com.hzhk.happyrent.ui.view.PredicateLayout;
import com.hzhk.happyrent.utils.MyPerference;
import com.hzhk.happyrent.utils.glide.ShowImageUtils;
import com.tamic.novate.Throwable;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ConfirmActivity extends AppCompatActivity {


    @BindView(R.id.activity_titlebar_left)
    ImageView activityTitlebarLeft;
    @BindView(R.id.activity_titlebar_center)
    TextView activityTitlebarCenter;
    @BindView(R.id.btn_comm)
    Button btnComm;
    @BindView(R.id.product_image)
    ImageView productImage;
    @BindView(R.id.product_title)
    TextView productTitle;
    @BindView(R.id.product_type)
    PredicateLayout productType;
    @BindView(R.id.product_value)
    TextView productValue;
    @BindView(R.id.rent_count)
    TextView rentCount;
    @BindView(R.id.rent_info)
    TextView rentInfo;
    @BindView(R.id.rent_total)
    TextView rentTotal;
    @BindView(R.id.pay_total)
    TextView payTotal;
    @BindView(R.id.zm_title)
    TextView zmTitle;
    @BindView(R.id.zm_grade)
    TextView zmGrade;
    @BindView(R.id.add_name)
    TextView addName;
    @BindView(R.id.add_phone)
    TextView addPhone;
    @BindView(R.id.add_title)
    TextView addTitle;
    @BindView(R.id.add_info)
    TextView addInfo;
    @BindView(R.id.act_user_phone)
    TextView actUserPhone;
    @BindView(R.id.act_user_name)
    ClearEditText actUserName;
    @BindView(R.id.act_user_relation)
    ClearEditText actUserRelation;
    @BindView(R.id.act_user_mess_leave)
    ClearEditText actUserMessLeave;
    @BindView(R.id.agreement)
    TextView agreement;
    @BindView(R.id.service_more)
    TextView serviceMore;
    @BindView(R.id.rl_service_more)
    RelativeLayout rlServiceMore;
    @BindView(R.id.ll_address_manage)
    LinearLayout llAddressManage;
    @BindView(R.id.pic_phone)
    ImageView picPhone;
    @BindView(R.id.check_agreement)
    ImageView checkAgreement;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        activityTitlebarCenter.setText("确认下单");
        getAddressDefault();
        if (!TextUtils.isEmpty(getIntent().getStringExtra("zm_grade"))) {
            zmGrade.setText("信用" + getIntent().getStringExtra("zm_grade"));
        } else {
            Toast.makeText(this, "芝麻分为空", Toast.LENGTH_SHORT).show();
//            finish();
        }
        if (!TextUtils.isEmpty(getIntent().getStringExtra("product_image"))) {
            ShowImageUtils.showImageView(this, productImage, getIntent().getStringExtra("product_image"));
        }
        if (!TextUtils.isEmpty(getIntent().getStringExtra("product_title"))) {
            productTitle.setText(getIntent().getStringExtra("product_title"));
        } else {
            Toast.makeText(this, "芝麻分为空", Toast.LENGTH_SHORT).show();
//            finish();
        }
        if (!TextUtils.isEmpty(getIntent().getStringExtra("product_description"))) {
            String description = getIntent().getStringExtra("product_description");
            if (description.contains("、")) {
                String[] tag = description.split("、");
                for (String s : tag) {
                    TextView textView = new TextView(this);
                    textView.setText(s);
                    textView.setPadding(5, 0, 5, 0);
                    textView.setTextColor(getResources().getColor(R.color.tab_red_80));
                    textView.setBackground(getResources().getDrawable(R.drawable.bg_red_hollow));
                    productType.addView(textView);
                }
            } else {
                TextView textView = new TextView(this);
                textView.setText(description);
                textView.setPadding(5, 0, 5, 0);
                textView.setTextColor(getResources().getColor(R.color.tab_red_80));
                textView.setBackground(getResources().getDrawable(R.drawable.bg_red_hollow));
                productType.addView(textView);
            }
        } else {
            Toast.makeText(this, "商品描述为空", Toast.LENGTH_SHORT).show();
//            finish();
        }
        if (!TextUtils.isEmpty(getIntent().getStringExtra("product_money"))) {
            productValue.setText("¥" + getIntent().getStringExtra("product_money") + "元");
        } else {
            Toast.makeText(this, "价值为空", Toast.LENGTH_SHORT).show();
//            finish();
        }
        if (!TextUtils.isEmpty(getIntent().getStringExtra("rent_count"))) {
            rentCount.setText(getIntent().getStringExtra("rent_count") + "期");
            rentInfo.setText("¥" + getIntent().getStringExtra("rent_money"));
        } else {
            Toast.makeText(this, "租期为空", Toast.LENGTH_SHORT).show();
//            finish();
        }
        //                    private String wx_pay_price;
//                    private String price;
//                    private String zu_money_total;
//                    private String service_money;
        if (!TextUtils.isEmpty(getIntent().getStringExtra("rent_total"))) {
            rentTotal.setText("¥" + getIntent().getStringExtra("rent_total"));
        } else {
            Toast.makeText(this, "租金为空", Toast.LENGTH_SHORT).show();
//            finish();
        }
        if (!TextUtils.isEmpty(getIntent().getStringExtra("rent_service_more"))) {
            rlServiceMore.setVisibility(View.VISIBLE);
            serviceMore.setText("¥" + getIntent().getStringExtra("rent_service_more"));
        }
        payTotal.setText("¥" + getIntent().getStringExtra("pay_total"));
    }

    @OnClick({R.id.activity_titlebar_left
            , R.id.btn_comm
            , R.id.add_phone
            , R.id.act_user_phone
            , R.id.agreement
            , R.id.check_agreement
            , R.id.tv_check_agreement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_titlebar_left:
                finish();
                break;
            case R.id.btn_comm:
                if (checkAgreement.isSelected()) {
                    placeAnOrder();
                } else {
                    Toast.makeText(this, "请先阅读并同意协议", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.check_agreement:
            case R.id.tv_check_agreement:
                checkAgreement.setSelected(!checkAgreement.isSelected());
                break;
            case R.id.add_phone:
                Intent intent = new Intent(this, AddressActivity.class);
                intent.putExtra("title", "请选择收货地址：");
                startActivityForResult(intent, 0);
                break;
            case R.id.act_user_phone:
                if (verifyStoragePermissions(this)) {
                    Uri uri = ContactsContract.Contacts.CONTENT_URI;
                    Intent intentPhone = new Intent(Intent.ACTION_PICK, uri);
                    startActivityForResult(intentPhone, 1);
                }
                break;
            case R.id.agreement:
                Intent intent1 = new Intent(this, AgreementActivity.class);
                intent1.putExtra("name", "用户租赁及服务协议");
                intent1.putExtra("id", "2");
                startActivity(intent1);
                break;
        }
    }

    private void placeAnOrder() {
        if (llAddressManage.getVisibility() == View.GONE) {
            Toast.makeText(this, "请添加收货地址", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(actUserPhone.getText().toString()) || TextUtils.isEmpty(actUserName.getText().toString()) || TextUtils.isEmpty(actUserRelation.getText().toString())) {
            Toast.makeText(this, "请添加联系人信息", Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", MyPerference.getInstance().getUserId());
        params.put("order_id", getIntent().getStringExtra("order_id"));
        params.put("emergency_person", actUserPhone.getText().toString());
        params.put("emergency_person_phone", actUserName.getText().toString());
        params.put("emergency_person_realation", actUserRelation.getText().toString());
        params.put("consignee", addName.getText().toString());
        params.put("address", addTitle.getText().toString() + addInfo.getText().toString());
        params.put("mobile", addPhone.getText().toString());
        if (!TextUtils.isEmpty(actUserMessLeave.getText().toString())) {
            params.put("message", actUserMessLeave.getText().toString());
        }
        HttpManager.getInstance().perform_post(API.ORDER_MAKE_SURE, params, new MyStringResponse(this) {
            @Override
            public void onError(Object tag, Throwable e) {
                Toast.makeText(ConfirmActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(Object tag, Throwable e) {
            }

            @Override
            public void onNext(Object tag, String message) {
                BaseModel baseModel = new Gson().fromJson(message, BaseModel.class);
                if (0 == baseModel.getErrCode()) {
//                    Toast.makeText(ConfirmActivity.this, R.string.product_rent_success, Toast.LENGTH_SHORT).show();
//                    Intent intent = new Intent(ConfirmActivity.this, HomeActivity.class);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                    startActivity(intent);
//                    startActivity(new Intent(ConfirmActivity.this, OrderListActivity.class));
                    OrderInfoModel orderInfoModel = new Gson().fromJson(message, OrderInfoModel.class);
//                    payFor(orderInfoModel.getData().getAlipay_sign());
                    Intent intent = new Intent(ConfirmActivity.this, PayChooseActivity.class);
                    intent.putExtra("pay_total", orderInfoModel.getData().getOrder_info().getWx_pay_price());
                    intent.putExtra("order_id", getIntent().getStringExtra("order_id"));
                    intent.putExtra("rent_total", getIntent().getStringExtra("rent_total"));
                    intent.putExtra("image_product", getIntent().getStringExtra("product_image"));
                    intent.putExtra("order_num", "");
                    intent.putExtra("order_time", "");
                    intent.putExtra("product_description", getIntent().getStringExtra("product_description"));
                    intent.putExtra("order_title", getIntent().getStringExtra("product_title"));
                    intent.putExtra("add_name", orderInfoModel.getData().getOrder_info().getConsignee());
                    intent.putExtra("add_phone", orderInfoModel.getData().getOrder_info().getMobile());
                    intent.putExtra("add_title", orderInfoModel.getData().getOrder_info().getAddress());
                    intent.putExtra("alipay_sign", orderInfoModel.getData().getAlipay_sign());
                    startActivity(intent);
                    finish();
                }else{
                    Toast.makeText(ConfirmActivity.this, baseModel.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void getAddressDefault() {
        Map<String, Object> params = new HashMap<>();
        params.put("user_id", MyPerference.getInstance().getUserId());
        HttpManager.getInstance().get(API.GET_DEFAULT_ADDRESS, params, new MyStringTransResponse(this) {

            @Override
            public void onError(Object tag, Throwable e) {

            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

            @Override
            public void onNext(String response) {
                AddressDefaultBean addressDefaultBean = new Gson().fromJson(response, AddressDefaultBean.class);
                if (addressDefaultBean.getErrCode() == 0 && addressDefaultBean.getData() != null) {
                    if (llAddressManage.getVisibility() == View.GONE) {
                        llAddressManage.setVisibility(View.VISIBLE);
                        addName.setVisibility(View.VISIBLE);
                        picPhone.setVisibility(View.VISIBLE);
                    }
                    addName.setText(addressDefaultBean.getData().getUser_name());
                    addPhone.setText(addressDefaultBean.getData().getPhone());
                    addTitle.setText(addressDefaultBean.getData().getArea());
                    addInfo.setText(addressDefaultBean.getData().getAddress());
                }
            }
        });
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0:
                if (resultCode == 1) {
                    if (data != null) {
                        if (llAddressManage.getVisibility() == View.GONE) {
                            llAddressManage.setVisibility(View.VISIBLE);
                            addName.setVisibility(View.VISIBLE);
                            picPhone.setVisibility(View.VISIBLE);
                        }
                        addName.setText(data.getStringExtra("address_name"));
                        addPhone.setText(data.getStringExtra("address_phone"));
                        addTitle.setText(data.getStringExtra("address"));
                        addInfo.setText(data.getStringExtra("address_info"));
                    }
                }
                break;
            case 1:
                if (data != null) {
                    //处理返回的data,获取选择的联系人信息
                    Uri uri = data.getData();
                    try {
                        String[] contacts = getPhoneContacts(uri);
                        actUserName.setText(contacts[0]);
                        actUserPhone.setText(contacts[1]);
                        actUserPhone.setTextColor(getResources().getColor(R.color.black_60));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                }
                break;
        }

    }

    private String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

    private static final String[] PERMISSION_EXTERNAL_STORAGE = new String[]{
            Manifest.permission.READ_CONTACTS
            , Manifest.permission.READ_PHONE_STATE
            , Manifest.permission.READ_EXTERNAL_STORAGE};
    private static final int REQUEST_EXTERNAL_STORAGE = 100;

    private boolean verifyStoragePermissions(Activity activity) {

        for (String s : PERMISSION_EXTERNAL_STORAGE) {
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(activity,
                    s)) {
                ActivityCompat.requestPermissions(activity, PERMISSION_EXTERNAL_STORAGE,
                        REQUEST_EXTERNAL_STORAGE);
                return false;
            }
        }
        return true;
    }
}
